<template>
	<!-- 个人列表页面 -->
	<echelon-solutions>
		<!-- 这里是顶部导航栏 -->
		<skyline-navigation title="个人账单"> </skyline-navigation>
		<!-- 这里是中间区域 -->
		<central-hub>
			<view class="container flex-column">
				<view class="flexGap flex-column" style="margin-top: 10rpx;">
					<button type="primary" @click="addDynamicTotal">总新增</button>
					<button type="primary" @click="addDynamic">新增</button>
					<!-- 使用自定义表格组件 -->
					<MyTreeTable :columns="columnsTotal" :data-source="sums" style="zoom: .7;">
						<!-- 自定义操作列 -->
						<template #operate="{ data }">
							<view class="flexGap">
								<button @click="handleEdit(data,true)" v-if="hasu('dynamic_bills')">编辑</button>
								<button type="warn" v-if="hasr('dynamic_bills')"
									@click="handleDelete(data,true)">删除</button>
							</view>
						</template>
					</MyTreeTable>
					<!-- 使用自定义表格组件 -->
					<MyTreeTable :columns="columns" :data-source="source" style="zoom: .7;">
						<!-- 自定义操作列 -->
						<template #operate="{ data }">
							<view class="flexGap">
								<button @click="handleEdit(data,true)" v-if="hasu('dynamic_bills')">编辑</button>
								<button type="warn" v-if="hasr('dynamic_bills')"
									@click="handleDelete(data,true)">删除</button>
							</view>
						</template>
					</MyTreeTable>
					<view v-for="(v,i) of sourceData">
						<view class="title" style="zoom: .5;">
							<view>{{v.title}}</view>
						</view>
						<!-- 使用自定义表格组件 -->
						<MyTreeTable :columns="columnsData" :data-source="v.displayedItems" style="zoom: .7;">
							<!-- 自定义操作列 -->
							<template #operate="{ data }">
								<view class="flexGap">
									<button @click="handleEdit(data)" v-if="hasu('dynamic_bills')">编辑</button>
									<button type="warn" v-if="hasr('dynamic_bills')"
										@click="handleDelete(data)">删除</button>
								</view>
							</template>
						</MyTreeTable>
					</view>
				</view>

				<MyPopup v-model="formsVis">
					<MyForm :fields="forms" @submit="submitForms" :submit-text="formsText" :filters="['id']">
					</MyForm>
				</MyPopup>
				<MyPopup v-model="popupVisible">
					<MyForm :fields="formFields" @submit="submit" :submit-text="submitText||'新增'" :filters="['id']">
					</MyForm>
				</MyPopup>

			</view>
		</central-hub>
	</echelon-solutions>
</template>

<script>
	export default {
		methods: {
			submitForms(formData) {
				if (formData.id) {
					this.$updatePublic('dynamictotal', formData, this.load);
				} else {
					this.$createPublic('dynamictotal', formData, this.load);
				}
			},
			addDynamicTotal() {
				this.forms = this.forms.filter(v => v.name !== 'id');
				this.formsText = '添加';
				this.formsVis = !this.formsVis;
			},
			addDynamic() {
				this.formFields = this.formFields.filter(v => v.name !== 'id');
				this.formFields[0].value = this.account_id; // 设置当前账号id，把它删除新增时会自动为上次的账号编辑的账号id设置进去
				this.formFields[0].disabled = false;
				this.submitText = '添加';
				this.popupVisible = !this.popupVisible;
			},
			handleEdit(data, flag) {
				if (flag) {
					this.forms.forEach(v => {
						v.value = data[v.name];
						return v;
					});
					this.forms[0].disabled = true;
					this.forms.unshift({
						label: "修改id",
						type: "text",
						name: "id",
						value: data.id,
						required: true,
						disabled: true,
					});
					this.formsText = '修改';
					this.formsVis = !this.formsVis;
					return false;
				}
				this.formFields.forEach(v => {
					v.value = data[v.name];
					return v;
				});
				this.formFields[0].disabled = true;
				this.formFields.unshift({
					label: "修改id",
					type: "text",
					name: "id",
					value: data.id,
					required: true,
					disabled: true,
				});
				this.formFields.forEach(it => {
					if (it.name === 'account_id') {
						it.value = data.account_id;
					}
				});
				this.submitText = '修改';
				this.popupVisible = !this.popupVisible;
			},
			handleDelete(data, flag) {
				if (flag) {
					this.$removePublic('dynamictotal', data, this.load);
				} else {
					this.$removePublic('dynamic_bill', data, this.load);
				}
			},
			submit(formData) {
				if (formData.id) {
					this.$updatePublic('dynamic_bill', formData, this.load);
				} else {
					this.$createPublic('dynamic_bill', formData, this.load);
				}
			},
			async initData(init = encodeURIComponent(JSON.stringify(this.$storage.get('login')))) {
				const info = JSON.parse(init);
				this.utils.info = info; // 个人信息
				this.account_id = info.account_id; // 账号id
				// 生成表单列表
				const generateFormField = (label, type, name, value = "", required = false, disabled = false, date =
					false,
					options) => {
					return {
						label,
						type,
						name,
						value,
						required,
						disabled,
						date,
						options
					};
				};
				const columns = [
					'ID,id,left',
					'报装日期,report_date',
					'账号,username',
					'网速/M,speed_Mbps', '包月/季度/半年/包年,rental_fee',
					'房东结算,landlord_settlement', '预结,advance_payment',
					'光猫网管收费,modem_fee', '费用,cost', '备注,notes',
					'联系电话,contact_phone', '地址,address', '到期,expirationDate',
					'日期已结1,payment_txt', '日期已结2,payment_completed', '操作,operate'
				];
				const fields = [
					generateFormField("为其新增", "text", "account_id", info.account_id, true,
						false,
						false, []),
					generateFormField("报装日期", "text", "report_date", '', false, false, true),
					generateFormField("账号", "text", "username"),
					generateFormField("网速/M", "text", "speed_Mbps"),
					generateFormField("套餐", "text", "rental_fee"),
					generateFormField("房东结算", "text", "landlord_settlement"),
					generateFormField("预结", "text", "advance_payment"),
					generateFormField("光猫收费", "text", "modem_fee"),
					generateFormField("备注", "text", "notes"),
					generateFormField("联系电话", "text", "contact_phone"),
					generateFormField("地址", "text", "address"),
					generateFormField("报装日期", "text", "expirationDate", '', false, false, true),
					generateFormField("日期已结1", "text", "payment_txt"),
					generateFormField("日期已结2", "text", "payment_completed")
				];
				const c = [
					generateFormField("日期", "text", "date", '', false, false, true),
					generateFormField("账号", "text", "username"),
					generateFormField("续费", "text", "renewal"),
					generateFormField("新装", "text", "newOutfit"),
					generateFormField("费用", "text", "cost"),
					generateFormField("业务员", "text", "salesman"),
					generateFormField("安装", "text", "installer"),
					generateFormField("数量", "text", "num"),
				];
				const myColumns = (columnData) => {
					return columnData.map(data => {
						const [title, key, fixed] = data.split(',');
						const column = {
							title,
							key
						};
						if (fixed) {
							column.fixed = fixed;
						}
						return column;
					});
				}
				this.columnsTotal = myColumns([
					'日期,date',
					'续费,renewal',
					'新装,newOutfit', '总收入,total',
					'费用,cost', '数量,num','业务员,salesman',
					'工资,salary'
				]);
				this.columns = myColumns([
					'日期,date',
					'账号,username',
					'续费,renewal',
					'新装,newOutfit',
					'费用,cost', '数量,num', '业务员,salesman', '安装,installer', '操作,operate'
				]);
				this.columnsData = myColumns(columns); // 生成表头 
				this.forms = c; // 表单列表 
				this.formFields = fields; // 表单列表 
				this.load();
			},
			async load() {
				this.source = await this.$listPublic('dynamictotal');
				this.sums = [this.source.reduce((acc, item) => {
					acc.renewal += item.renewal ? parseFloat(item.renewal) : 0;
					acc.newOutfit += item.newOutfit ? parseFloat(item.newOutfit) : 0;
					acc.cost += item.cost ? parseFloat(item.cost) : 0;
					acc.num += item.cost ? parseFloat(item.num) : 0;
					acc.total += (acc.renewal + acc.newOutfit) - acc.cost;
					return acc;
				}, {
					renewal: 0,
					newOutfit: 0,
					cost: 0,
					num: 0,
					total: 0,
				})];

				// 使用reduce方法计算指定属性的总和和其他功能
				const result = Object.values(this.source.reduce((acc, item) => {
					const key = item.salesman;

					if (!acc[key]) {
						acc[key] = {
							renewal: 0,
							newOutfit: 0,
							cost: 0,
							num: 0,
							total: 0,
							salesman:key,
						};
					}

					acc[key].renewal += item.renewal ? parseFloat(item.renewal) : 0;
					acc[key].newOutfit += item.newOutfit ? parseFloat(item.newOutfit) : 0;
					acc[key].cost += item.cost ? parseFloat(item.cost) : 0;
					acc[key].num += item.num ? parseFloat(item.num) : 0;
					acc[key].total = (acc[key].renewal + acc[key].newOutfit) - acc[key].cost;

					return acc;
				}, {}));

				// 计算所有salesman的总和
				const totalSum = Object.values(result).reduce((sum, item) => {
					sum.renewal += item.renewal;
					sum.newOutfit += item.newOutfit;
					sum.cost += item.cost;
					sum.num += item.num;
					sum.total += item.total;
					return sum;
				}, {
					renewal: 0,
					newOutfit: 0,
					cost: 0,
					num: 0,
					total: 0,
					salesman:'总',
				});
				this.sums = [...result, totalSum];



				const {
					data,
					allAccountInfo
				} = await this.$listPublic('dynamic_bill', this.utils.info);
				this.allAccountInfo = allAccountInfo;
				this.formFields.forEach(it => {
					if (it.name === 'account_id') {
						it.options = allAccountInfo.map(v => ({
							label: v.name,
							value: v.id
						}))
					}
				});
				this.sourceData = data;
				this.formsVis = false;
				this.popupVisible = false;

			}
		},
		data() {
			return {
				columnsTotal: [],
				sums: [],
				formsVis: false,
				formsText: '',
				forms: [],
				source: [],
				columns: [],
				columnsData: [],
				sourceData: [],
				formFields: [],
				popupVisible: false,
				submitText: '',
				utils: {
					info: null
				},
				account_id: '',
				allAccountInfo: []

			}
		},
		onLoad({
			data
		}) {
			this.initData(data);
		},
	}
</script>

<style scoped>
	.title {
		font-weight: bold;
		color: #000;
		border: solid 1px gainsboro;
		padding: 8px;
		box-sizing: border-box;
		border-bottom: none;
		border-top-left-radius: 4px;
		border-top-right-radius: 4px;
		box-shadow: 0 -1px 0 gainsboro;
		text-align: center;
		background: #db9b6d;
		font-size: 30px;
	}
</style>